package cn.sise.edu.crm.service.impl;

import cn.sise.edu.crm.domain.Permission;
import cn.sise.edu.crm.mapper.PermissionMapper;
import cn.sise.edu.crm.query.QueryObject;
import cn.sise.edu.crm.service.IPermissionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by chen on 2019/11/3.
 */
@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext apx;

    @Override
    public void insert(Permission permission) {
        permissionMapper.insert(permission);
    }

    @Override
    public void delete(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Permission selectById(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> selectAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public PageInfo<Permission> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        return new PageInfo<>(permissionMapper.selectForList(qo));
    }

    @Override
    public void reload() {
        //查询全部的权限
        List<Permission> permissions = permissionMapper.selectAll();
        Set<String> allNames = new HashSet<>();
        //放在set中
        for (Permission permission : permissions) {
            allNames.add(permission.getExpression());
        }
        //从中获取带有controller的注解的类
        Map<String, Object> beanMap = apx.getBeansWithAnnotation(Controller.class);
        //key代表在bean中的名字,value是对象
        Collection<Object> beans = beanMap.values();

        for (Object bean : beans) {
            //用反射获取代理类的方法.
            Method[] methods = bean.getClass().getSuperclass().getDeclaredMethods();
            for (Method method : methods) {
                //如果贴有注解,就进行操作
                if(method.isAnnotationPresent(RequiresPermissions.class)){
                    String[] strings = method.getAnnotation(RequiresPermissions.class).value();
                    //如果原来没有的就增加
                   if (!allNames.contains(strings[1])){
                       Permission permission = new Permission();
                       permission.setExpression(strings[1]);
                       permission.setName(strings[0]);
                       permissionMapper.insert(permission);
                   }
               }

            }
        }
    }

    @Override
    public List<String> selectByEmployeeId(Long id) {
        return permissionMapper.selectByEmployeeId(id);
    }
}
